{
 "cells": [
  {
   "metadata": {},
   "cell_type": "code",
   "source": "# 文本分类实例",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## Step1 导入相关包"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from transformers import AutoTokenizer, AutoModelForSequenceClassification"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": "",
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step2 加载数据"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import pandas as pd\n",
    "\n",
    "data = pd.read_csv(\"ChnSentiCorp_htl_all.csv\")\n",
    "data"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "data = data.dropna()\n",
    "data"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step3 创建Dataset"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from torch.utils.data import Dataset\n",
    "\n",
    "\n",
    "class MyDataset(Dataset):\n",
    "\n",
    "\tdef __init__(self) -> None:\n",
    "\t\tsuper().__init__()\n",
    "\t\tself.data = pd.read_csv(\"./ChnSentiCorp_htl_all.csv\")\n",
    "\t\tself.data = self.data.dropna()\n",
    "\n",
    "\tdef __getitem__(self, index):\n",
    "\t\treturn self.data.iloc[index][\"review\"], self.data.iloc[index][\"label\"]\n",
    "\n",
    "\tdef __len__(self):\n",
    "\t\treturn len(self.data)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "dataset = MyDataset()\n",
    "for i in range(5):\n",
    "\tprint(dataset[i])"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step4 划分数据集"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from torch.utils.data import random_split\n",
    "\n",
    "\n",
    "trainset, validset = random_split(dataset, lengths = [0.9, 0.1])\n",
    "len(trainset), len(validset)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "for i in range(10):\n",
    "\tprint(trainset[i])"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step5 创建Dataloader"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "import torch\n",
    "\n",
    "\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"hfl/rbt3\")\n",
    "\n",
    "\n",
    "def collate_func(batch):\n",
    "\ttexts, labels = [], []\n",
    "\tfor item in batch:\n",
    "\t\ttexts.append(item[0])\n",
    "\t\tlabels.append(item[1])\n",
    "\tinputs = tokenizer(texts, max_length = 128, padding = \"max_length\", truncation = True, return_tensors = \"pt\")\n",
    "\tinputs[\"labels\"] = torch.tensor(labels)\n",
    "\treturn inputs"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from torch.utils.data import DataLoader\n",
    "\n",
    "\n",
    "trainloader = DataLoader(trainset, batch_size = 32, shuffle = True, collate_fn = collate_func)\n",
    "validloader = DataLoader(validset, batch_size = 64, shuffle = False, collate_fn = collate_func)"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "next(enumerate(validloader))[1]"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step6 创建模型及优化器"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "from torch.optim import Adam\n",
    "\n",
    "\n",
    "model = AutoModelForSequenceClassification.from_pretrained(\"hfl/rbt3\")\n",
    "\n",
    "if torch.cuda.is_available():\n",
    "\tmodel = model.cuda()"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": "optimizer = Adam(model.parameters(), lr = 2e-5)",
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step7 训练与验证"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "def evaluate():\n",
    "\tmodel.eval()\n",
    "\tacc_num = 0\n",
    "\twith torch.inference_mode():\n",
    "\t\tfor batch in validloader:\n",
    "\t\t\tif torch.cuda.is_available():\n",
    "\t\t\t\tbatch = {k: v.cuda() for k, v in batch.items()}\n",
    "\t\t\toutput = model(**batch)\n",
    "\t\t\tpred = torch.argmax(output.logits, dim = -1)\n",
    "\t\t\tacc_num += (pred.long() == batch[\"labels\"].long()).float().sum()\n",
    "\treturn acc_num / len(validset)\n",
    "\n",
    "\n",
    "def train(epoch = 3, log_step = 100):\n",
    "\tglobal_step = 0\n",
    "\tfor ep in range(epoch):\n",
    "\t\tmodel.train()\n",
    "\t\tfor batch in trainloader:\n",
    "\t\t\tif torch.cuda.is_available():\n",
    "\t\t\t\tbatch = {k: v.cuda() for k, v in batch.items()}\n",
    "\t\t\toptimizer.zero_grad()\n",
    "\t\t\toutput = model(**batch)\n",
    "\t\t\toutput.loss.backward()\n",
    "\t\t\toptimizer.step()\n",
    "\t\t\tif global_step % log_step == 0:\n",
    "\t\t\t\tprint(f\"ep: {ep}, global_step: {global_step}, loss: {output.loss.item()}\")\n",
    "\t\t\tglobal_step += 1\n",
    "\t\tacc = evaluate()\n",
    "\t\tprint(f\"ep: {ep}, acc: {acc}\")"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step8 模型训练"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {
    "jupyter": {
     "is_executing": true
    }
   },
   "source": [
    "train()"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step9 模型预测"
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "source": [
    "sen = \"我觉得这家酒店不错，饭很好吃！\"\n",
    "id2_label = {0: \"差评！\", 1: \"好评！\"}\n",
    "model.eval()\n",
    "with torch.inference_mode():\n",
    "\tinputs = tokenizer(sen, return_tensors = \"pt\")\n",
    "\tinputs = {k: v.cuda() for k, v in inputs.items()}\n",
    "\tlogits = model(**inputs).logits\n",
    "\tpred = torch.argmax(logits, dim = -1)\n",
    "\tprint(f\"输入：{sen}\\n模型预测结果:{id2_label.get(pred.item())}\")"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-05T14:57:18.101700Z",
     "start_time": "2025-09-05T14:57:18.097657Z"
    }
   },
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "model.config.id2label = id2_label\n",
    "pipe = pipeline(\"text-classification\", model = model, tokenizer = tokenizer, device = 0)"
   ],
   "outputs": [],
   "execution_count": 19
  },
  {
   "cell_type": "code",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-05T14:57:19.900636Z",
     "start_time": "2025-09-05T14:57:19.881505Z"
    }
   },
   "source": [
    "pipe(sen)"
   ],
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': '好评！', 'score': 0.9963383674621582}]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 20
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "transformers",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
